package DianShang_2024.ds_02.clean

import org.apache.hudi.DataSourceWriteOptions.{PARTITIONPATH_FIELD, PRECOMBINE_FIELD, RECORDKEY_FIELD}
import org.apache.hudi.QuickstartUtils.getQuickstartWriteConfigs
import org.apache.spark.sql.{SparkSession, functions}
import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.functions.{col, desc, lit, row_number}

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

object clean02 {
  def main(args: Array[String]): Unit = {
    /*
        抽取ods_ds_hudi库sku_info表中昨天的分区（子任务一生成的分区）数据，并结合dim_sku_info最新分区现有的数据，根据id合并数据到dwd_ds_hudi库
        中dim_sku_info的分区表（合并是指对dwd层数据进行插入或修改，需修改的数据以id为合并字段，根据create_time排序取最新的一条），分区字段
        为etl_date且值与ods_ds_hudi库的相对应表该值相等，并添加dwd_insert_user、dwd_insert_time、dwd_modify_user、dwd_modify_time四
        列,其中dwd_insert_user、dwd_modify_user均填写“user1”。若该条数据第一次进入数仓dwd层则dwd_insert_time、dwd_modify_time均填写
        当前操作时间，并进行数据类型转换。若该数据在进入dwd层时发生了合并修改，则dwd_insert_time时间不变，dwd_modify_time存当前操作时间，其余
        列存最新的值。id作为primaryKey，dwd_modify_time作为preCombineField。使用spark-shell查询表dim_sku_info的字
        段id、sku_desc、dwd_insert_user、dwd_modify_time、etl_date，条件为最新分区的数据，id大于等于15且小于等于20，并且按照id升序排序，将结果
        截图粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下
     */
    val spark=SparkSession.builder()
      .master("local[*]")
      .appName("数据清洗第二题")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()

    val ods_path="hdfs://192.168.40.110:9000/user/hive/warehouse/ods_ds_hudi02.db/sku_info"
    val dwd_path="hdfs://192.168.40.110:9000/user/hive/warehouse/dwd_ds_hudi02.db/dim_sku_info"

    val day:Calendar=Calendar.getInstance()
    day.add(Calendar.DATE,-1)
    val yesterday=new SimpleDateFormat("yyyMMdd").format(day.getTime)

    val ods1=spark.read.format("hudi").load(ods_path)
    ods1.createOrReplaceTempView("ods1")
    val ods=spark.read.format("hudi").load(ods_path)
      .where("etl_date=(select max(etl_date) from ods1)")     //  比赛的话这里用yesterday
      .drop("etl_date")
      .withColumn("dwd_insert_user",lit("user1"))
      .withColumn(
        "dwd_insert_time",
        lit(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
      )
      .withColumn("dwd_modify_user",lit("user1"))
      .withColumn(
        "dwd_modify_time",
        lit(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
      )


    //  dwd
    val dwd1=spark.read.format("hudi").load(dwd_path)
    dwd1.createOrReplaceTempView("dwd1")
    val dwd=spark.read.format("hudi").load(dwd_path)
      .where("etl_date=(select max(etl_date) from dwd1)")
      .drop("etl_date")

    dwd.unionAll(ods)
      .withColumn(
        "row",
        row_number().over(Window.partitionBy("id").orderBy(desc("create_time")))
      )
      .withColumn(
        "dwd_insert_time",
        functions.min("dwd_insert_time").over(Window.partitionBy("id"))
      )
      .where(col("row")===1)
      .drop("row")
      .withColumn("etl_date",lit(yesterday))
      .write.mode("append")
      .format("hudi")
      .options(getQuickstartWriteConfigs)
      .option(RECORDKEY_FIELD.key(),"id")
      .option(PRECOMBINE_FIELD.key(),"dwd_modify_time")
      .option(PARTITIONPATH_FIELD.key(),"etl_date")
      .option("hoodie.table.name","dim_sku_info")
      .save(dwd_path)



    spark.close()
  }

}
